package com.demo.jianjunhuang.catimgwebview;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.AEADBadTagException;

/**
 * @author jianjunhuang.me@foxmail.com
 *         create on 2017/7/11.
 */

public class CatWebViewClient extends WebViewClient {

    public static List<String> imgUrls = new ArrayList<>();

    private boolean canInterceptImg = false;

    private boolean canImgClick = false;

    private String defaultImgInAssets;

    private static final String TAG = "CatWebViewClient";

    public void setCanInterceptImg(boolean canInterceptImg, @NonNull String defaultImgInAssets) {
        this.canInterceptImg = canInterceptImg;
        this.defaultImgInAssets = defaultImgInAssets;
    }

    public void setCanImgClick(boolean canImgClick) {
        this.canImgClick = canImgClick;
    }

    public boolean canImgClick() {
        return canImgClick;
    }


    public boolean canInterceptImg() {
        return canInterceptImg;
    }

    public String getJSInterfaceName() {
        return "imagelistener";
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        view.getSettings().setJavaScriptEnabled(true);
        Log.d(TAG, "onPageStarted: ");
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        if (Build.VERSION.SDK_INT >= 21 && canInterceptImg) {
            String url = request.getUrl().toString();
            if (!imgUrls.contains(url) && checkIsPicUrl(url)) {
                Log.d(TAG, "shouldInterceptRequest: " + imgUrls.size() + "   " + request.getUrl().toString());
                return mResponse(view);
            } else {
                Log.d(TAG, "shouldInterceptRequest: imgUrls have contain " + imgUrls.size() + "   " + url);
            }
        }
        return super.shouldInterceptRequest(view, request);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        WebResourceResponse response = null;
        if (Build.VERSION.SDK_INT < 21 && canInterceptImg) {
            if (!imgUrls.contains(url) && checkIsPicUrl(url)) {
                response = mResponse(view);
                Log.d(TAG, "shouldInterceptRequest: " + url);
            }
        }
        return response;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.d(TAG, "shouldOverrideUrlLoading: " + url);
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        Log.d(TAG, "onLoadResource: " + url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        Log.d(TAG, "onPageFinished: " + url);
        if (canImgClick) {
            addImageClickListener(view);
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.d(TAG, "shouldOverrideUrlLoading: " + request.getUrl().toString());
        }
        return super.shouldOverrideUrlLoading(view, request);
    }


    public void addImageClickListener(final WebView view) {
        Log.w(TAG, "addImageClickListener: addImageClickListener ");

        view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{ if(objs[i].id == null || objs[i].id == \"\"){objs[i].id = objs[i].src;}"
                + "    objs[i].onclick=function()  " +
                "    {   "
                + "        window.imagelistener.onImageUrl(this.src,this.id);  " +
                "    }  " +
                "}" +
                "})()");

    }

    public void changeIdAndSrc(String url) {
        String js = "javascript:({var objs = document.getElement})()";
    }

    /**
     * 本地图片
     *
     * @return
     */
    private WebResourceResponse mResponse(WebView view) {

        if (defaultImgInAssets == null) {
            Log.e(TAG, "mResponse: defaultImgStream is null");
        }
        WebResourceResponse webResourceResponse = null;
        try {
            webResourceResponse = new WebResourceResponse("image/png", "UTF-8", view.getContext().getAssets().open(defaultImgInAssets));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return webResourceResponse;
    }

    private boolean checkIsPicUrl(String url) {
        Pattern p = Pattern.compile("https?://.+\\.(jpg|gif|png|bmp|mif|miff|tif|tiff|eps|wmf|jpeg|ico|dib|svg|tga|cut|pic|PNG|JPG|JPEG)");
        Matcher m = p.matcher(url);
        return m.matches();
    }

}
